<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽</title>
    <style>
        .box {
            position: absolute;
            top: 0;
            left: 0;
            display: inline-block;
            width: 500px;
            height: 500px;
            border: 1px solid #000;
        }

        .header {
            height: 50px;
            background-color: aqua;
        }

        .content {
            height: 450px;
            background-color: blueviolet;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="header"></div>
        <div class="content"></div>
    </div>

    <script src="./jquery-1.9.0.min.js"></script>
    <script>
        selectMove($('.box'), $('.header'));

        function selectMove(element, target) {
            var element = element[0];
            var target = target[0];
            var isDown = false;
            var x = 0,
                y = 0,
                l = 0,
                t = 0,
                w = 0,
                h = 0
            target.onmouseenter = function () {
                target.style.cursor = 'move';
            }
            target.onmouseleave = function () {
                target.style.cursor = 'default';
            }
            // 鼠标按下
            target.onmousedown = function (e) {
                var rect = element.getBoundingClientRect();
                //获取x坐标和y坐标
                x = e.clientX;
                y = e.clientY;
                //获取左部和顶部的偏移量
                l = rect.left;
                t = rect.top;
                w = rect.width;
                h = rect.height;
                //开关打开
                isDown = true;
                //设置样式  
                target.style.cursor = 'move';
            }
            //鼠标移动
            document.onmousemove = function (e) {
                if (isDown == false) {
                    return;
                }
                //获取x和y
                var nx = e.clientX;
                var ny = e.clientY;
                //计算移动后的左偏移量和顶部的偏移量
                var nl = (nx - x) + l;
                var nt = (ny - y) + t;

                if (nl <= 0) {
                    nl = 0;
                } else if (nl + w > window.innerWidth) {
                    nl = window.innerWidth - w;
                }
                if (nt <= 0) {
                    nt = 0;
                } else if (nt + h > window.innerHeight) {
                    nt = window.innerHeight - h;
                }
                element.style.left = nl + 'px';
                element.style.top = nt + 'px';
            }
            //鼠标抬起事件
            document.onmouseup = function () {
                //开关关闭
                isDown = false;
                target.style.cursor = 'default';
            }
        }
    </script>
</body>

</html>